/*
  "name": "大山后台管理系统",
  "version": "1.0",
  "description": "大山中后台管理系统",
  "author": "大山",
  "date": "2023-04-22",
  "license": "MIT",
*/

const bodyParser = require('body-parser');
const jsonParser = bodyParser.json({ limit: '1000mb' });
const resbody = require('../utils/resbody');
const utils = require('../utils/utils');
const token = require('../utils/token');
const connection = require('../utils/sql');
const mysql = require('mysql');
const escape = mysql.escape;
const jwt = require("jsonwebtoken");
const { log } = require('debug/src/node');

module.exports = (app) => {
	
	// 验证token
	const whiteList = ['/api/login'];
	let userTokenData;
	
	app.use((req,res,next) => {
		if(!whiteList.includes(req.url)) {
			token.verifyToken(req.headers.authorization).then(res => {
				userTokenData = res
				next()
			}).catch(e => {
				// token过期时的err值："message": "jwt expired",
				// token无效时的err值："message": "jwt malformed | invalid token | invalid signature",
				// 没有token的err值："message": "jwt must be provided"
				let msg = token.tokenMsg().find(item => item.type === e.message)['msg']
				// res.status(200).send(res.json(resbody.getFailResult({}, msg)))
				res.json(resbody.getFailResult({}, msg, 401))
			})
		} else {
			next()
		}
	})
	
	// 获取随机id
	app.get('/api/getUuId', (req,res) => {
		const id = utils.randomNumber();
		res.json(resbody.getSuccessResult({id}))
	})
	
	// 获取字典
	app.get('/api/getDictType/:dictType', (req,res) => {
		const { dictType } = req.params
		
		const sql = `SELECT id, dictLabel, dictType, listClass, cssClass, dictValue, createTime FROM dictData WHERE dictType='${dictType}'`
		connection(sql, (error, result, fileds) => {
		    if(error){
		        console.log(error)
		        res.json(resbody.getFailResult(error))
		    }else{
		        res.json(resbody.getSuccessResult(result))
		    }
		})
	})
}
